package com.sh169.action.admin;

import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.view.ServerRedirectView;
import org.nutz.mvc.view.VoidView;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import com.sh169.pojos.Order;
import com.sh169.pojos.OrderInfo;

@IocBean(name="orderController")
@InjectName("orderController")
@At("/admin/order")
public class OrderController {
	
	// 查看未完成的订单 需分页
	@Ok("tiles:admin.order.viewUnfinishedOrders")
	public List<Order> viewUnfinishedOrders(){
		List<Order> os = dao.query(Order.class, Cnd.where("state","!=",Order.STATE_FINISH), null);
		return os.size()==0?null: os;
	}
	//查看已完成的订单  需分页
	@Ok("tiles:admin.order.viewFinishedOrders")
	public List<Order> viewFinishedOrders(){
		List<Order> os = dao.query(Order.class, Cnd.where("state","=",Order.STATE_FINISH), null);
		return os.size()==0?null: os;
	}
	// 查看订单详情
	@Ok("tiles:admin.order.show")
	public Order show(@Param("id")int id){
		if(id<1)return null;
		
		Order o = dao.fetch(Order.class,id);
		if(o != null){
			dao.fetchLinks(o, "orderInfos");
			List<OrderInfo> ois = o.getOrderInfos();
			if(ois!=null && ois.size()>0){
				dao.fetchLinks(ois, "product");
			}
		}
		return o;
		
	}
	//编辑订单
	@Ok("tiles:admin.order.edit")
	public Order edit(@Param("id")int id){
		return show(id);
	}
	// 更新订单（主要修改状态）
	public View update(@Param("::o.")Order order){
		if(order == null || order.getId()<1) return new VoidView();
		Order source = dao.fetch(Order.class,order.getId());
		if(source == null) return new VoidView();
		
		source.setAddress(order.getAddress());
		source.setMan(order.getMan());
		source.setPhone(order.getPhone());
		source.setState(order.getState());
		source.setTip(order.getTip());
		dao.update(source);
		return new ServerRedirectView("/admin/order/show.do?id="+source.getId());
		
	}
	// 删除订单
	@Ok("redirect:/admin/order/viewUnfinishedOrders")
	public void delete(@Param("id") final int id){
		if(id<1) return ;
		Trans.exec(new Atom(){
			public void run() {
				dao.clear(OrderInfo.class,Cnd.where("orderid","=",id));
				dao.delete(Order.class, id);
			}
		});
	}
	@Inject
	private Dao dao ;
	public void setDao(Dao dao){
		this.dao = dao;
	}
}
